// -*- coding: utf-8 -*- 
/**
 * Project: AlgorithmsLearn
 *
 * @author: yanking
 * Create time: 2022-04-08 17:35
 * IDE: IntelliJ IDEA
 * Introduction:
 */
package com.LeetCodeT.DateTrain;

import java.util.*;

public class levelOrder {
    List<List<Integer>> ans = new ArrayList<>();

    /**
     * 多叉树的层序遍历
     */
    public List<List<Integer>> levelOrder(Node root) {
        if (root == null) {
            return ans;
        }

        Queue<Node> queue = new ArrayDeque<>();
        List<Integer> list = new ArrayList<>();
        queue.offer(root);
        int layer = 1, nLayers = 0;
        ans.add(new ArrayList<Integer>() {{
            add(root.val);
        }});
        while (!queue.isEmpty()) {
            Node node = queue.poll();
            layer--;
            for (Node child : node.children) {
                nLayers++;
                list.add(child.val);
                queue.offer(child);
            }
            if (layer == 0) {
                if (!list.isEmpty()) {
                    List<Integer> tmp = new ArrayList<>(list);
                    ans.add(tmp);
                    list.clear();
                }
                layer = nLayers;
                nLayers = 0;
            }
        }
        return ans;
    }


    class Node {
        public int val;
        public List<Node> children;

        public Node() {
        }

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, List<Node> _children) {
            val = _val;
            children = _children;
        }
    }


}
